package com.carpedil.shirodemo.system.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.carpedil.shirodemo.system.model.Menu;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Mapper 接口
 *
 * @author carpedil
 * @since 2021-01-05
 */
@Repository
public interface MenuMapper extends BaseMapper<Menu> {

  @Select(
      "select distinct menu.menu_id,"
          + "   menu.parent_id,"
          + "   menu.menu_name,"
          + "   menu.url,"
          + "   menu.perms,"
          + "   menu.order_num,"
          + "   menu.icon "
          + "   from    user,"
          + "           role,"
          + "           user_role,"
          + "           menu,"
          + "           role_menu "
          + "        where user.user_id = user_role.user_id "
          + "          and role.role_id = user_role.role_id "
          + "          and role.role_id = role_menu.role_id "
          + "          and menu.menu_id = role_menu.menu_id "
          + "          and user.username = #{username}")
  @ResultMap(value = "com.carpedil.shirodemo.system.mapper.MenuMapper.menuMap")
  List<Menu> selectMenuByUserName(@Param("username") String username);

  List<Menu> selectAllTree();

  @Select(
      " select menu_id, parent_id, menu_name, url, perms, order_num, create_time, modify_time, icon from menu where parent_id = #{parentId} order by order_num")
  List<Menu> selectByParentId(@Param("parentId") Integer parentId);

  @Update(
      "UPDATE menu AS prev "
          + "  JOIN menu AS next "
          + "  ON (prev.`menu_id` = #{currentId} AND next.`menu_id` = #{swapId}) "
          + "  OR (prev.`menu_id` = #{swapId} AND next.`menu_id` = #{currentId}) "
          + "  SET prev.`order_num` = next.`order_num`, next.`order_num` = prev.`order_num` ")
  void swapOrder(@Param("currentId") Integer currentId, @Param("swapId") Integer swapId);
  /**
   * 获取排序字段的最大值
   *
   * @return 排序字段的最大值
   */
  @Select("select ifnull(max(order_num), 0) from menu")
  Integer selectMaxOrderNum();
  /**
   * 查询带功能权限的菜单树
   *
   * @return Menu菜单树集合
   */
  List<Menu> selectAllMenuAndCountOperator();
}
